package com.kxf.zxingmini.zxing;

import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.kxf.zxingmini.R;

/**
 * @ProjectName: AndroidTestDemo
 * @Package: com.kxf.zxingmini.zxing
 * @ClassName: DecodeHelper
 * @Description: 解码的工具类
 * @Author: kuangxuefeng
 * @qq: 1024883177
 * @CreateDate: 2021/3/24 15:10
 */
public class DecodeHelper {
    /**
     * Decode the data within the viewfinder rectangle, and time how long it took. For efficiency,
     * reuse the same reader objects from one decode to the next.
     *
     * @param data   The YUV preview frame.
     * @param width  The width of the preview frame.
     * @param height The height of the preview frame.
     */
    public Result decode(byte[] data, int width, int height) {
        System.out.println("开始解码===>>>");
        byte[] rotatedData = new byte[data.length];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++)
                rotatedData[x * height + height - y - 1] = data[x + y * width];
        }
        int tmp = width; // Here we are swapping, that's the difference to #11
        width = height;
        height = tmp;

        data = rotatedData;

        Result rawResult = null;
        PlanarYUVLuminanceSource source = buildLuminanceSource(data, width, height);
        if (source != null) {
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            MultiFormatReader multiFormatReader = new MultiFormatReader();;
            try {
                rawResult = multiFormatReader.decodeWithState(bitmap);
            } catch (ReaderException e) {
                e.printStackTrace();
            } finally {
                multiFormatReader.reset();
            }
        }
        return rawResult;
    }

    public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
        // Go ahead and assume it's YUV rather than die.
        return new PlanarYUVLuminanceSource(data, width, height, 0, 0,
                width, height, false);
    }
}
